package com.nbicc.common.exception;

import com.nbicc.common.Const;
import com.nbicc.common.ResponseObj;
import lombok.extern.slf4j.Slf4j;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.HttpStatus;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

/**
 * Created by li on 17/12/22.
 * 在controller里执行逻辑代码时出的异常。譬如NullPointerException。
 */
@Slf4j
@ControllerAdvice
public class RunningExceptionHandler extends ResponseEntityExceptionHandler {

    @ExceptionHandler(value = DuplicateKeyException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseObj DuplicateKeyExceptionHandler(HttpServletRequest request, HttpServletResponse response , Exception e) {
        ResponseObj responseObj = new ResponseObj(Const.HTTP_STATUS_FAIL);
        responseObj.setError("不允许重复插入");
        responseObj.setMessage(e.getMessage());
        log.error(responseObj.toString());
        return responseObj;
    }

    @ExceptionHandler(value = Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    @ResponseBody
    public ResponseObj ExceptionHandler(HttpServletRequest request, HttpServletResponse response , Exception e){
        ResponseObj responseObj = new ResponseObj(Const.HTTP_STATUS_FAIL);
        responseObj.setError(StringUtils.isEmpty(e.getMessage()) ? "未知错误" : e.getMessage());
        responseObj.setMessage(e.getMessage());
        log.error(responseObj.toString());
        return responseObj;
    }


}
